package com.cxw.healthserver.interceptor;

import com.cxw.healthserver.annotation.PassToken;
import com.cxw.healthserver.entity.Token;
import com.cxw.healthserver.entity.User;
import com.cxw.healthserver.response.BaseResponse;
import com.cxw.healthserver.service.AuthService;
import com.cxw.healthserver.service.UserService;
import com.cxw.healthserver.utils.gson.JsonUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.lang.reflect.Method;

@Component
public class UserInterceptor implements HandlerInterceptor {


    private final AuthService authService;

    private final UserService userService;

    public UserInterceptor(AuthService authService, UserService userService) {
        this.authService = authService;
        this.userService = userService;
    }


    //全局拦截器拦截请求访问
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是url映射的方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method        method        = handlerMethod.getMethod();
        //如果被@passToken标注方法,则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //将token放到http请求里，用户携带token访问请求
        String              token        = request.getHeader("token");
        BaseResponse<Token> baseResponse = authService.checkToken(token);
        if (!baseResponse.isSuccess()) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.println(JsonUtils.parseBean2json(baseResponse));
            writer.flush();
            writer.close();
            return false;
        }
        Token tokenBean = baseResponse.getData();

        User user = userService.getUserByUserid(tokenBean.getUserid());
        if (user == null) {
            throw new RuntimeException("用户不存在，请重新登录!");
        }
        request.setAttribute("currentUser", user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}